import React from 'react'
import * as FileSaver from "file-saver";
import * as XLSX from "xlsx";



export const ExportToExcel = ({ dataSource, fileName, children }) => {
  const fileType =
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8";
  const fileExtension = ".xlsx";

  const exportToCSV = (dataSource, fileName) => {
    const ws = XLSX.utils.json_to_sheet(dataSource);
    const wb = { Sheets: { data: ws }, SheetNames: ["data"] };
    const excelBuffer = XLSX.write(wb, { bookType: "xlsx", type: "array" });
    const data = new Blob([excelBuffer], { type: fileType });
    FileSaver.saveAs(data, fileName + fileExtension);
  };

  return (
    <a onClick={(e) => exportToCSV(dataSource, fileName)}>
      {children}
    </a>
  );
};


export const ImportToExcel = ({ onImportExcel, children }) => {

  const [state, setState] = React.useState({
    data: [] /* Array of Arrays e.g. [["a","b"],[1,2]] */,
    cols: [] /* Array of column objects e.g. { name: "C", K: 2 } */
  })

  const handleChange= (e) => {
    const files = e.target.files;
    if (files && files[0]) handleFile(files[0]);
  }
  
  const handleFile = (file /*:File*/)=> {
    /* Boilerplate to set up FileReader */
    const reader = new FileReader();
    const rABS = !!reader.readAsBinaryString;
    reader.onload = e => {
      /* Parse data */
      const bstr = e.target.result;
      const wb = XLSX.read(bstr, { type: rABS ? "binary" : "array" });
      /* Get first worksheet */
      const wsname = wb.SheetNames[0];
      const ws = wb.Sheets[wsname];
      console.log(rABS, wb);
      /* Convert array of arrays */
      const data = XLSX.utils.sheet_to_json(ws, { header: 1 });
      /* Update state */
      setState({ data: data, cols: make_cols(ws["!ref"]) });
    };
    if (rABS) reader.readAsBinaryString(file);
    else reader.readAsArrayBuffer(file);
  }

  React.useEffect(() => {
    onImportExcel && onImportExcel(state)
  }, [state]);

  return (
      <div style={{ position: 'relative', display: 'inline-block' }}>
        <input style={{ opacity: 0, position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, width: '-webkit-fill-available', zIndex: 2 }}type="file" accept={SheetJSFT} onChange={handleChange}/>
        <div>{ children }</div>
        {/* <table className="table table-striped">
          <thead>
            <tr>
              {state.cols.map(c => (
                <th key={c.key}>{c.name}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {state.data.map((r, i) => (
              <tr key={i}>
                {state.cols.map(c => (
                  <td key={c.key}>{r[c.key]}</td>
                ))}
              </tr>
            ))}
        </tbody>
        </table> */}
      </div>
  );
};


export const ImportToCSV = ({ children }) => {
  const [tables, setTables] = React.useState(null);
  const importExcelToJson = (file) => {
    // Construct a FileReader object to read the file
    const fileReader = new FileReader();
    const rABS = !!fileReader.readAsBinaryString;
    // Return Promise to facilitate the delivery of processed json to back-end processing
    return new Promise((resolve, reject) => {
      fileReader.onerror = () => {
        fileReader.abort();
        reject("Failed to read the file");
      };
      fileReader.onload = () => {
        try {
          // Deconstruct the result read by fileReader to result
          const { result } = fileReader;
          // Use XLSX to read binary stream to generate workbook
          const workbook = XLSX.read(result, { type: rABS ? "binary" : "array" });
          let data = [];
          let htmls = []
          // Read the Sheet, only one is read, if it is multiple sheets, you may need to use objects to store the data of each sheet
          // The read result is converted into a json object, and then resolved
          for (const sheet in workbook.Sheets) {
            if (workbook.Sheets.hasOwnProperty(sheet)) {
              //Use sheet_to_json method to convert excel into json data
              // XLSX.utils.sheet_to_csv：生成CSV格式
              // XLSX.utils.sheet_to_txt：生成纯文本格式
              // XLSX.utils.sheet_to_html：生成HTML格式
              // XLSX.utils.sheet_to_json：输出JSON格式
              htmls = htmls.concat(
                XLSX.utils.sheet_to_html(workbook.Sheets[sheet])
              );
              data = data.concat(
                XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
              );
              break;
            }
          }
          // document.getElementById('csv-tables').innerHTML = htmls;
          // setTables(htmls)
          resolve(data);
        } catch (err) {
          console.log(err, "error");
          reject(err);
        }
      };
      fileReader.readAsBinaryString(file);
    });
  };

  const importExcel = async (e) => {
    const file = e.target.files[0];
    const data = await importExcelToJson(file);
    console.log(data, "data");
    let header = [];
    for (const [key] of Object.entries(data[0])) {
      header.push(key);
    }
    console.log(header, "header");
  };

  return (
    <div style={{ position: 'relative', display: 'inline-block' }}>
      <input style={{ opacity: 0, position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, width: '-webkit-fill-available', zIndex: 2 }} type="file" accept={SheetJSFT} onChange={importExcel} />
      <div>{ children}</div>
    </div>
  );
}




/* list of supported file types */
const SheetJSFT = [
  "xlsx",
  "xlsb",
  "xlsm",
  "xls",
  "xml",
  "csv",
  "txt",
  "ods",
  "fods",
  "uos",
  "sylk",
  "dif",
  "dbf",
  "prn",
  "qpw",
  "123",
  "wb*",
  "wq*",
  "html",
  "htm"
]
  .map(function(x) {
    return "." + x;
  })
  .join(",");

/* generate an array of column objects */
const make_cols = refstr => {
  let o = [],
    C = XLSX.utils.decode_range(refstr).e.c + 1;
  for (var i = 0; i < C; ++i) o[i] = { name: XLSX.utils.encode_col(i), key: i };
  return o;
};
